package org.dylan.common.model;

import org.springframework.util.Assert;

/**
 * 数据查询参数
 * 
 * @author dylan
 * 
 */
public class BaseQueryParam implements QueryParam {
	private String field;
	private Object value;
	private MatchType matchType=MatchType.EQ;
	//
	private boolean required = false;
	private Object escapeValue = null;

	/**
	 * 是否需要进行数据逃逸处理
	 * 
	 * @return
	 */
	public boolean shouldEscape() {
		return !required && matchs(value, escapeValue);
	}

	private boolean matchs(Object value, Object escapeValue) {
		if (value == null && escapeValue == null) {
			return true;
		}
		return value.equals(escapeValue);
	}

	public BaseQueryParam field(String field) {
		Assert.notNull(field);
		this.field = field;
		return this;
	}

	public BaseQueryParam value(Object value) {
		this.value = value;
		return this;
	}

	public BaseQueryParam matchType(MatchType matchType) {
		this.matchType = matchType;
		return this;
	}

	public BaseQueryParam isRequired(boolean required) {
		this.required = required;
		return this;
	}

	public BaseQueryParam setEscapeValue(Object escapeValue) {
		this.escapeValue = escapeValue;
		return this;
	}

	public String field() {
		return field;
	}

	public Object value() {
		return value;
	}

	public MatchType matchType() {
		return matchType;
	}

	public boolean isRequired() {
		return required;
	}

	public Object escapeValue() {
		return escapeValue;
	}

	/**
	 * 值匹配类型
	 * 
	 * @author dylan
	 * 
	 */
	public static enum MatchType {
		/**
		 * 精确匹配,=
		 */
		EQ,
		/**
		 * 不等,<>
		 */
		NE,
		/**
		 * like匹配,like
		 */
		LIKE,
		/**
		 * like匹配,%like
		 */
		LIKE_LEFT,
		/**
		 * like匹配,like%
		 */
		LIKE_RIGHT,
		/**
		 * like匹配,%like%
		 */
		LIKE_ANYWHERE,
		/**
		 * 大于,>
		 */
		GT,
		/**
		 * 大于等于,>=
		 */
		GE,
		/**
		 * 小于,<
		 */
		LT,
		/**
		 * 小于等于,<=
		 */
		LE,
		/**
		 * between,这时的value应该BetweenValue实例
		 */
		BETWEEN,
		/**
		 * in匹配，这时的value应该是一个数组或者一个集合Collection
		 */
		IN,
		/**
		 * null匹配
		 */
		NULL,
		/**
		 * not null匹配
		 */
		NOT_NULL
	}

	/**
	 * 对于between匹配，其值应该是BetweenValue的实例
	 * 
	 * @author dylan
	 * 
	 */
	public static class BetweenValue {
		private Object minValue;
		private Object maxValue;

		public BetweenValue(Object min, Object max) {
			Assert.notNull(min);
			Assert.notNull(max);
		}

		public Object min() {
			return minValue;
		}

		public Object max() {
			return maxValue;
		}
	}

}
